package com.woniuxy.oldmanapi.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.oldmanapi.entity.Bedlog;
import com.woniuxy.oldmanapi.mapper.BedMapper;
import com.woniuxy.oldmanapi.mapper.BedlogMapper;
import com.woniuxy.oldmanapi.mapper.OlderMapper;
import com.woniuxy.oldmanapi.xvo.BedLogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BedLogService {
    @Autowired
    BedlogMapper bedlogMapper;
    @Autowired
    BedMapper bedMapper;
    @Autowired
    OlderMapper olderMapper;

    public PageInfo<BedLogVo> selectBedLogByname(int now, int size, String name) {
        PageHelper.startPage(now,size);
        List<BedLogVo> list = bedlogMapper.selectBedLogByname(name);
        PageInfo<BedLogVo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    @Transactional
    public void changeBed(Bedlog bedlog) {
        int oid = bedlog.getOlderId();
        int oldbedId = bedlog.getOldbedId();
        int newbedId = bedlog.getNewbedId();
        Bedlog log = bedlogMapper.selectLogByOid(oid);
        if(log != null){
            bedlog.setId(log.getId());
            bedlogMapper.updateByPrimaryKey(bedlog);
        }else {
            bedlogMapper.insert(bedlog);
        }
        olderMapper.updateOlderBed(oid,newbedId);
        bedMapper.updateBedStateById(oldbedId);
        bedMapper.updateBedStateByNewId(newbedId);
    }

    public void deleteBedLog(int id) {
        bedlogMapper.deleteByPrimaryKey(id);
    }
}
